<template>
  <!-- 车主数据》车辆颜色 -->
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="4"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <div id="Chartdiv" style="paddingBottom:10px;background:#F2F4F8;">
      <div class="chartSearch">
        <div>
          <el-date-picker
            v-model="searchDate"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            style="width:220px;">
            <!-- :picker-options="pickerOptions" -->
          </el-date-picker>
          <el-radio-group v-model="radio" @change="changeDate">
            <el-radio-button v-for="(item, index) in radioList" :key="index" :label="item.value" plain>{{item.text}}</el-radio-button>
          </el-radio-group>
        </div>
        <div>
          <router-link :to="{ path: '/report/retail/DefeatedCustomers/index' }" class="topbtmone">
          战败客户明细
          </router-link>
        </div>
      </div>
      <div class="Chartmain" style="display:flex;justify-content: space-between;">
        <div class="Chartf">
          <Chart1 :option="option1" :containerStyle="{height: '300px'}"/>
        </div>
        <div class="Chartf Chartleft">
          <Chart1 :option="option2" :containerStyle="{height: '300px'}"/>
        </div>
      </div>
    </div>
    <div>
      <div class="maintop">
        <el-tabs class="lazyLoadTab" v-model="activeName" @tab-click="handleClick">
          <el-tab-pane class="lazyLoadTabPane" label="团队" name="first"></el-tab-pane>
        </el-tabs>
      </div>

      <div class="tabShow">
        <!-- <potenCusModal v-if="activeName === 'first'" :dataSource="dataSource"/> -->
        <FilterTable
          ref="table"
          :columns="columns"
          height="auto"
          v-loading="loading"
          :mergeCellMethod="objectSpanMethod"
          :dataSource="dataSource"
          :isPagination="false"
          :isSelectColumn="false"
          :isColumnFilter="false"
          selectionType="single"
          :onColumnsChange="columns => this.columns = columns"
        ></FilterTable>
      </div>
    </div>


  </div>
</template>

<script>
import {
  queryNewPotentialCount,
  getEmployeeInfo
 } from '@/api/report/retail/potenCusInsertStat';
import {
  queryDefeatReport,
  queryFailCountByPeriod
 } from '@/api/report/retail/CauseOfDefeat';
import { getOrgTeam, getUserByOrgId } from '@/api/report/retail/clueFunnelAnalysis';
import { dictionary } from '@/utils/dictMixin';
import Chart1 from '@/charts/preSale/chart1';
import { authority } from '@/utils/authMixin';
import { arrayObjDeWeight, integration, GetPercent, computedAll, getTextByJs } from '@/utils/index';
import { ObjectAssign, sortRule } from '@/components/DataMerge';
import moment from 'moment';
export default {
  name: 'CauseOfDefeat',
  mixins: [dictionary,authority],
  components: {
    Chart1
  },
  data() {
    return {
      columns: this.createTableColumns(),
      dataSource: [],
      loading:false,
      initDataSource: [],
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      visible: false,
      dialogTitle: '',
      handleType: '',
      searchDate: '',
      conf:{ add: '新增', edit: '编辑', show: '显示' },
      option1: {},
      option2: this.createOption2(),
      radio:'day',
      radioList: [{ value:'day', text:'日' }, { value:'week', text:'周' }, { value:'month', text:'月' }, { value:'quarter', text:'季' }, { value:'year', text:'年' }],
      activeName: 'first',
    };
  },
  watch: {
    searchDate(val){
      console.log(val);
      if (val && val.length > 0) {
        this.fetchParams.startDate = val[0];
        this.fetchParams.endDate = val[1];
        this.queryDefeatReport()
      }
    }
  },
  methods: {
    createTopFilters() {
      return [
        {
          type: 'DATE',
          label: '日期',
          fieldName: 'datetime',
          placeholder: '',
          dateType: 'exactdate',
          initialValue: moment().format("YYYY-MM-DD")
          // change: (val, fieldName) => {
          //   // console.log(val,fieldName)
          //   this.quarterTime = val;
          // }
        },
        {
          type: 'SELECT',
          label: '销售小组',
          fieldName: 'orgId',
          placeholder: '请选择...',
          itemList: [],
          change: val => {
            // console.log(val,fieldName)
            this.getUserByOrgId(val);
          }
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '销售顾问',
          fieldName: 'consultants',
          placeholder: '请选择...',
          itemList: []
        }
      ];
    },
    createOption1(){
      return {
        title : {
          text: '战败原因分布',
          left: '24',
          top: '24',
        },
        tooltip: {
          trigger: 'item',
          formatter: "{b} <br/>数量: {c} ({d}%)",
          backgroundColor: 'rgba(0,0,0,0.75)',
        },
        legend: {
          icon: 'circle',
          itemWidth: 8,
          itemHeight: 8,
          textStyle: {
            color: 'rgba(0,4,10,0.45)'
          },
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: '30%',
          // formatter: '{name}',
          formatter: function (params, index) {
            // 超出省略
            params = params.toString();
            var maxlength= 8;
            if (params.length>maxlength) {
              return params.substring(0, maxlength-1)+'...';
            } else{
              return params;
            }
          }
        },
        series: [
            {
              name:'战败原因分布',
              type:'pie',
              center: ['40%', '50%'],
              radius: ['40%', '70%'],
              avoidLabelOverlap: false,
              label: {
                normal: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  show: false,
                  textStyle: {
                    fontSize: '30',
                    fontWeight: 'bold'
                  }
                }
              },
              labelLine: {
                normal: {
                  show: false
                }
              },
              data:[]
            }
        ],
        color:['#FF4D4F', '#73D13D', '#36CFC9', '#FFC53D', '#6940E9', '#FFEC3D', '#597EF7', '#40A9FF', '#FF7A45', '#FFA940', '#BAE637', '#1890FF'],
      }
    },
    createOption2(){
      return {
        title : {
          text: '战败竞品情况分布',
          left: '24',
          top: '24',
        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b}: {c} ({d}%)",
          backgroundColor: 'rgba(0,0,0,0.75)',
        },
        legend: {
          icon: 'circle',
          itemWidth: 8,
          itemHeight: 8,
          textStyle: {
            color: 'rgba(0,4,10,0.45)'
          },
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: '30%',
          // formatter: '{name}',
          formatter: function (params, index) {
            // 超出省略
            params = params.toString();
            var maxlength= 8;
            if (params.length>maxlength) {
              return params.substring(0, maxlength-1)+'...';
            } else{
              return params;
            }
          }
          // data:[{intentLevel:'A',proportion:20},{intentLevel:'B',proportion:20},{intentLevel:'C',proportion:20},{intentLevel:'H',proportion:20},{intentLevel:'O',proportion:20}]
        },
        series: [
          {
            name:'战败竞品情况分布',
            type:'pie',
            center: ['40%', '50%'],
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false,
                textStyle: {
                  fontSize: '30',
                  fontWeight: 'bold'
                }
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data:[]
          }
        ],
        color:['#FFD164', '#597EF7', '#BAE637', '#5FD9D4', '#7B98F9', '#FF956B'],
      }
    },

    async queryDefeatReport() {
      const res = await queryDefeatReport(this.fetchParams);
      // console.log('销售顾问', res)
      if (res.resultCode === 200) {
        let arr = [],arr2 = [],option1 = this.createOption1(),option2 = this.createOption2();
        res.data.reasonList.map(x=>{
          arr.push({
            name:x.basedataName || '未知',
            value:x.total
          })
        })
        option1.series[0].data = arr;
        res.data.competitorList.map(x=>{
          arr2.push({
            name:x.failSeries || '未知',
            value:x.total
          })
        })
        option2.series[0].data = arr2;

        this.option1 = option1;
        this.option2 = option2;
        // // console.log(this.option1)
        // this.initDataSource = res.data.detailVO;
      }
    },

    async queryFailCountByPeriod() {
      this.loading = true;
      const res = await queryFailCountByPeriod(this.fetchParams);
      if (res.resultCode === 200) {
        this.loading = false;
        let list = res.data;
        list = sortRule(list, 'orgId');
        let moreColumns = this.moreColumns()
        let all = computedAll([...this.columns,...moreColumns],list)
        all['orgId'] = 'all';
        all['consultant'] = 'all';
        all['orgName'] = '全部';
        all['consultantName'] = '全部';
        list.unshift(all);
        list.forEach(x=>{
            x['monthSame'] = GetPercent(x.monthTotal - x.lastMonthTotal,x.lastMonthTotal)
            x['monthSequential'] = GetPercent(x.monthTotal - x.previewMonthTotal,x.previewMonthTotal)
            x['monthTotalRate'] = GetPercent(x.monthTotal,x.monthClueTotal)
            x['quarterSame'] = GetPercent(x.quarterTotal - x.lastQuarterTotal,x.lastQuarterTotal)
            x['quarterSequential'] = GetPercent(x.quarterTotal - x.previewQuarterTotal,x.previewQuarterTotal)
            x['quarterTotalRate'] = GetPercent(x.quarterTotal,x.quarterClueTotal)
            x['yearSame'] = GetPercent(x.yearTotal - x.lastYearTotal,x.lastYearTotal)
            x['yearTotalRate'] = GetPercent(x.yearTotal,x.yearClueTotal)
        })
        console.log(list)
        this.dataSource = list;
        // table数据处理
        // this.ProcessData()
        // console.log(orgList)
      }
    },
    async getOrgTeam() {
      const res = await getOrgTeam();
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'orgId').itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getUserByOrgId(val) {
      const res = await getUserByOrgId({ orgId: val });
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'consultants').itemList = res.data.map(x => ({ value: x.userId, text: x.userName }));
        this.topFilterList.find(item => item.fieldName === 'consultants').initialValue = '';
      }
    },
    changeHandle(val) {
      // console.log(val)
      if (val.datetime) {
        val.startDate = val.datetime;
        val.endDate = val.datetime;
      }else{
        val.startDate = moment().format("YYYY-MM-DD");
        val.endDate = moment().format("YYYY-MM-DD");
      }
      if (val.consultants && val.consultants.length > 0) {
        val.consultant = getTextByJs(val.consultants);
      }
      this.fetchParams = Object.assign({}, val);
      this.radio = 'day';
      this.queryDefeatReport()
      this.queryFailCountByPeriod()
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    collapseHandle() {
      // this.$nextTick(() => {
      //   this.BaseTable.EXECUTE_RESET_HEIGHT();
      // });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    changeDate(value){
      // console.log(this.rowDate)
      let val = {...this.fetchParams}
      if (!val.datetime) {
        val.datetime = moment().format("YYYY-MM-DD");
      }
      if (value) {
        switch (value) {
          case 'day':
            val.startDate = val.datetime;
            val.endDate = val.datetime;
            break;
          case 'week':
            var weekOfday = moment(val.datetime, 'YYYY-MM-DD').format('E'); //计算指定日期是这周第几天
            var last_monday = moment(val.datetime)
              .subtract(weekOfday - 1, 'days')
              .format('YYYY-MM-DD'); //周一日期
            var last_sunday = moment(val.datetime)
              .add(7 - weekOfday, 'days')
              .format('YYYY-MM-DD'); //周日日期
            // console.log(last_monday,last_sunday)
            val.startDate = last_monday;
            val.endDate = last_sunday;
            break;
          case 'month':
            var start_monthday = moment(val.datetime)
              .startOf('month')
              .format('YYYY-MM-DD'); //月初日期
            var last_monthday = moment(val.datetime)
              .endOf('month')
              .format('YYYY-MM-DD'); //月末日期
            // console.log(start_monthday,last_monthday)
            val.startDate = start_monthday;
            val.endDate = last_monthday;
            break;
          case 'quarter':
            val.startDate = moment(val.datetime).startOf('quarter').format("YYYY-MM-DD")
            val.endDate = moment(val.datetime).endOf('quarter').format("YYYY-MM-DD");
            // console.log(val.startDate,val.endDate)
            break;
          case 'year':
            var start_yearday = moment(val.datetime).startOf('year').format('YYYY-MM-DD'); //年初日期
            var last_yearday = moment(val.datetime).endOf('year').format('YYYY-MM-DD'); //年末日期
            val.startDate = start_yearday;
            val.endDate = last_yearday;
            break;
          case 'date':
            val.startDate = val.datetime[0] ? val.datetime[0]:undefined;
            val.endDate = val.datetime[1] ? val.datetime[1]:undefined;
            break;
          default:
            val.startDate = moment().format("YYYY-MM-DD");
            val.endDate = moment().format("YYYY-MM-DD");
            break;
        }
      }
      this.fetchParams = Object.assign({}, val);
      this.queryDefeatReport()
    },
    // 修改日期组件
    changeTemplateType(val){
      switch (val) {
        case 'day':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdate';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'week':
          console.log('week')
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'week';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'month':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'month';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'quarter':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'quarter';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'year':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'year';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        case 'date':
          this.topFilterList.find(item=>item.fieldName==='datetime').type = 'RANGE_DATE';
          this.topFilterList.find(item=>item.fieldName==='datetime').dateType = 'exactdaterange';
          this.topFilterList.find(item=>item.fieldName==='datetime').initialValue = '';
          break;
        default:
          this.topFilterList.find(item => item.fieldName === 'datetime').type = 'DATE';
          this.topFilterList.find(item => item.fieldName === 'datetime').dateType = 'exactdate';
          this.topFilterList.find(item => item.fieldName === 'datetime').initialValue = '';
          break;
      }
    },
    moreColumns() {
      return [
        {
          title: '上年同月战败数量-算同比用',
          dataIndex: 'lastMonthTotal'
        },
        {
          title: '上年同季度战败数量-算同比用',
          dataIndex: 'lastQuarterTotal'
        },
        {
          title: '上年战败数量-算同比用',
          dataIndex: 'lastYearTotal'
        },
        {
          title: '月留档量',
          dataIndex: 'monthClueTotal'
        },
        {
          title: '上月战败数量-算环比用',
          dataIndex: 'previewMonthTotal'
        },
        {
          title: '上季度战败数量-算环比用',
          dataIndex: 'previewQuarterTotal'
        },
        {
          title: '季留档量',
          dataIndex: 'quarterClueTotal'
        },
        {
          title: '年留档量',
          dataIndex: 'yearClueTotal'
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '销售小组',
          dataIndex: 'orgName'
        },
        {
          title: '销售顾问',
          dataIndex: 'consultantName'
        },
        {
          title: '日战败',
          dataIndex: 'dayTotal'
        },
        {
          title: '周战败',
          dataIndex: 'weekTotal'
        },
        {
          title: '月度',
          align: 'center',
          children: [
            {
              title: '月战败',
              dataIndex: 'monthTotal',
            },
            {
              title: '月同比',
              dataIndex: 'monthSame',
              render: props => {
                return <span style={props.row.monthSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSame}</span>;
              }
            },
            {
              title: '月环比',
              dataIndex: 'monthSequential',
              render: props => {
                return <span style={props.row.monthSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.monthSequential}</span>;
              }
            },
            {
              title: '月战败率',
              dataIndex: 'monthTotalRate',
            },
          ]
        },
        {
          title: '季度',
          align: 'center',
          children: [
            {
              title: '季战败',
              dataIndex: 'quarterTotal',
            },
            {
              title: '季同比',
              dataIndex: 'quarterSame',
              render: props => {
                return <span style={props.row.quarterSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSame}</span>;
              }
            },
            {
              title: '季环比',
              dataIndex: 'quarterSequential',
              render: props => {
                return <span style={props.row.quarterSequential.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.quarterSequential}</span>;
              }
            },
            {
              title: '季战败率',
              dataIndex: 'quarterTotalRate',
            },
          ]
        },
        {
          title: '年度',
          align: 'center',
          children: [
            {
              title: '年战败',
              dataIndex: 'yearTotal',
            },
            {
              title: '年同比',
              dataIndex: 'yearSame',
              render: props => {
                return <span style={props.row.yearSame.indexOf("-") != -1 ? 'color:#FF4D4F':'color:#73D13D'}>{props.row.yearSame}</span>;
              }
            },
            {
              title: '年战败率',
              dataIndex: 'yearTotalRate',
            },
          ]
        },
      ];
    },

    // 合并行或列的计算方法
    // row:当前行 column:当前列 rowIndex:当前行号 columnIndex:当前列号
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          row.orgName = '全部';
          return [1, 2];
        } else {
          // 与上一行不相等
          if (row.orgId !== (this.dataSource[rowIndex - 1] || {}).orgId) {
            // 与上一行不相等,与下一行相等
            if (row.orgId === (this.dataSource[rowIndex + 1] || {}).orgId) {
              return {
                rowspan: this.dataSource.filter(x => row.orgId === x.orgId).length || 1,
                colspan: 1
              };
            } else {   // 与上一行不相等,与下一行不相等
              return [1, 1];
            }
          } else {     // 与上一行相等
            return [0, 0];
          }
        }
      } else if (columnIndex === 1) {
        if (rowIndex === 0) {
          return [0, 0];
        }
      }
    },
  },
  mounted() {
    // this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getOrgTeam()
    this.changeHandle({})
    // this.queryDefeatReport()
    // this.queryFailCountByPeriod()
  }
};
</script>

<style lang="less" scoped>
#Chartdiv{

  .chartSearch{
    display:flex;
    align-items: center;
    justify-content: space-between;
    padding:12px 32px;
    background:#fff;
    border-bottom: 1px solid rgba(0,4,10,0.08);
    .topbtmone{
      color: #2089F9;
    }
  }
  .Chartmain{
    background:#fff;
    .Chartleft{
      border-left: 1px dashed rgba(0,4,10,0.08);
    }
  }
}
.Chartf{
  width:49.6%;
  // max-height: 400px;
  .ChartTop{
    font-size: 16px;
    font-weight: 600;
    line-height: 58px;
    padding-left:32px;
  }
}


.maintop{
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  overflow: hidden;
  background:#FFF;
  padding-left: 12px;
  padding-right: 12px;
  border-bottom: 1px solid rgba(0,4,10,0.08);
  .lazyLoadTab {
    /deep/ .el-tabs__header,.is-top{
      margin-bottom: 0;
    }
    /deep/ .el-tabs__active-bar{
      height: 4px;
    }
    /deep/ .el-tabs__nav-wrap::after{
      height: 0;
    }
  }
}

.tabShow{
  min-height: 300px;
}
</style>
